package android.meetingatsb.location

import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.meetingatsb.R
import android.net.Uri
import android.provider.Settings

class CheckPermissionsActivity : Activity() {
    var needPermissions = arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE)

    private var isNeedCheck = true

    override fun onResume() {
        super.onResume()
        if (isNeedCheck) { checkPermissions(needPermissions) }
    }

    private fun checkPermissions(permissions: Array<String>) {
        val needRequestPermissonList = findDeniedPermissions(permissions)
        if (needRequestPermissonList.size > 0) {
            val array = needRequestPermissonList.toTypedArray()
            val method = javaClass.getMethod("requestPermissions",
                    *arrayOf<Class<*>>(Array<String>::class.java, Int::class.java))

            method.invoke(this, array, PERMISSON_REQUESTCODE)
        }
    }


    private fun findDeniedPermissions(permissions: Array<String>): List<String> {
        val needRequestPermissonList = ArrayList<String>()
        for (perm in permissions) {
            val checkSelfMethod = javaClass.getMethod("checkSelfPermission", String::class.java)
            val shouldShowRequestPermissionRationaleMethod = javaClass.getMethod("shouldShowRequestPermissionRationale",
                    String::class.java)
            if (checkSelfMethod.invoke(this, perm) as Int != PackageManager.PERMISSION_GRANTED || shouldShowRequestPermissionRationaleMethod.invoke(this, perm) as Boolean) {
                needRequestPermissonList.add(perm)
            }
        }
        return needRequestPermissonList
    }

    private fun verifyPermissions(grantResults: IntArray): Boolean {
        for (result in grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    @TargetApi(23)
    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<String>, paramArrayOfInt: IntArray) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog()
                isNeedCheck = false
            }
        }
    }


    private fun showMissingPermissionDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle(R.string.notifyTitle)
        builder.setMessage(R.string.notifyMsg)

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.action_cancel,
                { _, which -> finish() })

        builder.setPositiveButton(R.string.action_ok,
                { _, which -> startAppSettings() })

        builder.setCancelable(false)

        builder.show()
    }

    private fun startAppSettings() {
        val intent = Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse("package:" + packageName)
        startActivity(intent)
    }

    override fun onBackPressed() {
        this.finish()
    }

    companion object {
        private val PERMISSON_REQUESTCODE = 0
    }

}